package com.hunliji.monitor.web.facade.impl;

import com.hunliji.common.exception.WarnException;
import com.hunliji.common.response.PageData;
import com.hunliji.monitor.service.api.BusinessTableFollowersService;
import com.hunliji.monitor.service.api.BusinessTableRecordService;
import com.hunliji.monitor.service.api.UserInfoService;
import com.hunliji.monitor.service.api.model.bo.BusinessTableFollowersBO;
import com.hunliji.monitor.service.api.model.bo.BusinessTableRecordBO;
import com.hunliji.monitor.service.api.model.bo.UserInfoBO;
import com.hunliji.monitor.service.api.model.param.QueryBusinessTableFollowersParam;
import com.hunliji.monitor.service.api.model.param.QueryBusinessTableRecordParam;
import com.hunliji.monitor.share.constants.BusinessRecordConstants;
import com.hunliji.monitor.share.utils.PageDataUtil;
import com.hunliji.monitor.web.facade.BusinessTableRecordFacade;
import com.hunliji.monitor.web.model.param.AddBusinessTableRecordParam;
import com.hunliji.monitor.web.model.param.EditTableRecordParam;
import com.hunliji.monitor.web.model.vo.BusinessTableFollowersVO;
import com.hunliji.monitor.web.model.vo.BusinessTableRecordVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务表记录
 * @author wuchen
 */
@Service
public class BusinessTableRecordFacadeImpl implements BusinessTableRecordFacade {
    private static final Logger logger = LoggerFactory.getLogger(BusinessTableRecordFacadeImpl.class);
    @Resource
    private BusinessTableRecordService businessTableRecordService;
    @Resource
    private BusinessTableFollowersService businessTableFollowersService;
    @Resource
    private UserInfoService userInfoService;
    /**
     * 添加记录
     * @param addBusinessTableRecordParam
     */
    @Override
    public void add(AddBusinessTableRecordParam addBusinessTableRecordParam) {
        if(Objects.isNull(addBusinessTableRecordParam.getDatabaseName()) || StringUtils.isBlank(addBusinessTableRecordParam.getTableName())){
            throw new WarnException("表名或者库名未填写");
        }
        //在插入之前，先根据表名称和库名称进行一次查询
        QueryBusinessTableRecordParam queryBusinessTableRecordParam = new QueryBusinessTableRecordParam();
        queryBusinessTableRecordParam.setTableName(addBusinessTableRecordParam.getTableName());
        queryBusinessTableRecordParam.setDbName(addBusinessTableRecordParam.getDatabaseName());
        List<BusinessTableRecordBO> currentTableRecordBOList = businessTableRecordService.query(queryBusinessTableRecordParam);
        if(!CollectionUtils.isEmpty(currentTableRecordBOList)){
            throw new WarnException("已经存在同样库名和表名的记录");
        }
        BusinessTableRecordBO businessTableRecordBO = new BusinessTableRecordBO();
        businessTableRecordBO.setDatabaseName(addBusinessTableRecordParam.getDatabaseName());
        businessTableRecordBO.setTableName(addBusinessTableRecordParam.getTableName());
        businessTableRecordBO.setBusinessRemarks(addBusinessTableRecordParam.getBusinessRemarks());
        businessTableRecordBO = businessTableRecordService.add(businessTableRecordBO);


        //添加关注人
        try {
            if(!CollectionUtils.isEmpty(addBusinessTableRecordParam.getFollowersList())){
                for (Long followersId: addBusinessTableRecordParam.getFollowersList()){
                    BusinessTableFollowersBO businessTableFollowersBO = new BusinessTableFollowersBO();
                    businessTableFollowersBO.setTableRecordId(businessTableRecordBO.getId());
                    businessTableFollowersBO.setFollowersType(BusinessRecordConstants.FollowersType.FOLLOWERS.name());
                    businessTableFollowersBO.setUserId(followersId);
                    businessTableFollowersService.add(businessTableFollowersBO);
                }
            }
        }catch (Exception e){
            logger.warn("添加关注人异常");
        }

//        //添加维护人
//        try {
//            if(!CollectionUtils.isEmpty(addBusinessTableRecordParam.getFollowersList())){
//                for (Long maintainerId: addBusinessTableRecordParam.getFollowersList()){
//                    BusinessTableFollowersBO businessTableFollowersBO = new BusinessTableFollowersBO();
//                    businessTableFollowersBO.setTableRecordId(businessTableRecordBO.getId());
//                    businessTableFollowersBO.setFollowersType(BusinessRecordConstants.FollowersType.MAINTAINER.name());
//                    businessTableFollowersBO.setUserId(maintainerId);
//                    businessTableFollowersService.add(businessTableFollowersBO);
//                }
//            }
//        }catch (Exception e){
//            logger.warn("添加维护人异常");
//        }
    }

    @Override
    public void update(EditTableRecordParam editTableRecordParam) {
        BusinessTableRecordBO tableRecordBO = businessTableRecordService.queryById(editTableRecordParam.getId());
        if(Objects.isNull(tableRecordBO)){
            throw new WarnException("无法查询到表记录");
        }
        if(StringUtils.isNotBlank(editTableRecordParam.getBusinessRemarks()) && (!editTableRecordParam.getBusinessRemarks().equals(tableRecordBO.getBusinessRemarks()))){
            tableRecordBO.setBusinessRemarks(editTableRecordParam.getBusinessRemarks());
            businessTableRecordService.update(tableRecordBO);
        }
        //更新关注人
        //查询当前全部的关注人
        QueryBusinessTableFollowersParam queryBusinessTableFollowersParam = new QueryBusinessTableFollowersParam();
        queryBusinessTableFollowersParam.setRecordIdList(Arrays.asList(tableRecordBO.getId()));
        List<BusinessTableFollowersBO> followersBOList = businessTableFollowersService.query(queryBusinessTableFollowersParam);
        //历史的关注人
        List<BusinessTableFollowersBO> historyFollowersBOList = followersBOList.stream().filter(s->s.getFollowersType().equals(BusinessRecordConstants.FollowersType.FOLLOWERS.name())).collect(Collectors.toList());
        List<Long> currentFollowerIdList = editTableRecordParam.getFollowersList();
        //识别哪些需要删除 历史中存在，当前不存在
        List<BusinessTableFollowersBO> deleteList = new ArrayList<>();
        for (BusinessTableFollowersBO followersBO:historyFollowersBOList){
            if(!currentFollowerIdList.contains(followersBO.getUserId())){
                followersBO.setDeleted(Boolean.TRUE);
                businessTableFollowersService.update(followersBO);
            }
        }
        //识别哪些需要新增，当前存在，历史不存在
        List<Long> historyFollowersIdList = historyFollowersBOList.stream().map(BusinessTableFollowersBO::getUserId).collect(Collectors.toList());
        for (Long currentFollowerId:currentFollowerIdList){
            if(!historyFollowersIdList.contains(currentFollowerId)){
                BusinessTableFollowersBO businessTableFollowersBO = new BusinessTableFollowersBO();
                businessTableFollowersBO.setTableRecordId(tableRecordBO.getId());
                businessTableFollowersBO.setFollowersType(BusinessRecordConstants.FollowersType.FOLLOWERS.name());
                businessTableFollowersBO.setUserId(currentFollowerId);
                businessTableFollowersService.add(businessTableFollowersBO);
            }
        }
    }

    /**
     * 删除记录
     * @param id
     */
    @Override
    public void delete(Long id) {
        QueryBusinessTableRecordParam queryBusinessTableRecordParam = new QueryBusinessTableRecordParam();
        queryBusinessTableRecordParam.setId(id);
        queryBusinessTableRecordParam.setPageNum(1);
        queryBusinessTableRecordParam.setPageSize(1);
        PageData<BusinessTableRecordBO> pageData = businessTableRecordService.queryPage(queryBusinessTableRecordParam);
        if(pageData.getTotalCount() > 0){
            BusinessTableRecordBO businessTableRecordBO = pageData.getList().get(0);
            businessTableRecordBO.setDeleted(Boolean.TRUE);
            businessTableRecordService.update(businessTableRecordBO);
            return;
        }
        throw new WarnException("无法查询到记录");
    }

    @Override
    public PageData<BusinessTableRecordVO> queryPage(QueryBusinessTableRecordParam queryBusinessTableRecordParam) {
        //查询记录
        PageData<BusinessTableRecordBO> pageData = businessTableRecordService.queryPage(queryBusinessTableRecordParam);
        if(pageData.getTotalCount() > 0){
            //筛选出id列表
            List<BusinessTableRecordBO> businessTableRecordBOList = pageData.getList();
            List<Long> bstIdList = businessTableRecordBOList.stream().map(BusinessTableRecordBO::getId).collect(Collectors.toList());
            QueryBusinessTableFollowersParam queryBusinessTableFollowersParam = new QueryBusinessTableFollowersParam();
            queryBusinessTableFollowersParam.setRecordIdList(bstIdList);
            //去查询关联记录
            List<BusinessTableFollowersBO> businessTableFollowersBOList = businessTableFollowersService.query(queryBusinessTableFollowersParam);
            //对其进行分组，分别是关注人和维护人
            //维护人
            List<Long> maintainerIdList = new ArrayList<>();
            //key:表记录id value:关注人列表
            Map<Long,List<BusinessTableFollowersBO>> maintainerOfRecordMap = new HashMap<>();
            //关注人
            List<Long> followersIdList = new ArrayList<>();
            //key:表记录id value:关注人列表
            Map<Long,List<BusinessTableFollowersBO>> followerOfRecordMap = new HashMap<>();
            for (BusinessTableFollowersBO businessTableFollowersBO:businessTableFollowersBOList){
//                //如果是维护人
//                if(BusinessRecordConstants.FollowersType.MAINTAINER.name().equals(businessTableFollowersBO.getFollowersType())){
//                    maintainerIdList.add(businessTableFollowersBO.getUserId());
//                    List<BusinessTableFollowersBO> maintainerOfRecordList = maintainerOfRecordMap.get(businessTableFollowersBO.getTableRecordId());
//                    if(CollectionUtils.isEmpty(maintainerOfRecordList)){
//                        maintainerOfRecordList = new ArrayList<>();
//                    }
//                    maintainerOfRecordList.add(businessTableFollowersBO);
//                    maintainerOfRecordMap.put(businessTableFollowersBO.getTableRecordId(),maintainerOfRecordList);
//
//                }
                //如果是关注人
                if(BusinessRecordConstants.FollowersType.FOLLOWERS.name().equals(businessTableFollowersBO.getFollowersType())){
                    followersIdList.add(businessTableFollowersBO.getUserId());
                    List<BusinessTableFollowersBO> followersOfRecordList = followerOfRecordMap.get(businessTableFollowersBO.getTableRecordId());
                    if(CollectionUtils.isEmpty(followersOfRecordList)){
                        followersOfRecordList = new ArrayList<>();
                    }
                    followersOfRecordList.add(businessTableFollowersBO);
                    followerOfRecordMap.put(businessTableFollowersBO.getTableRecordId(),followersOfRecordList);
                }

            }
//            //查询维护人
//            Map<Long, UserInfoBO> maintainerUserMap = userInfoService.getByIds(maintainerIdList);
            //查询关注人
            Map<Long,UserInfoBO> followersUserMap = userInfoService.getByIds(followersIdList);
            //返回数据
            List<BusinessTableRecordVO> businessTableRecordVOList = new ArrayList<>();
            //循环构建返回数据
            for (BusinessTableRecordBO businessTableRecordBO:businessTableRecordBOList){
                BusinessTableRecordVO businessTableRecordVO = new BusinessTableRecordVO();
                businessTableRecordVO.setId(businessTableRecordBO.getId());
                businessTableRecordVO.setDatabaseName(businessTableRecordBO.getDatabaseName());
                businessTableRecordVO.setTableName(businessTableRecordBO.getTableName());
                businessTableRecordVO.setBusinessRemarks(businessTableRecordBO.getBusinessRemarks());
                //设置维护人
//                List<BusinessTableFollowersVO> maintainerOfRecordVOList = new ArrayList<>();
//
//                List<BusinessTableFollowersBO> maintainerOfRecordList = maintainerOfRecordMap.get(businessTableRecordBO.getId());
//                if(!CollectionUtils.isEmpty(maintainerOfRecordList)){
//                    for (BusinessTableFollowersBO businessTableFollowersBO:maintainerOfRecordList){
//                        UserInfoBO userInfoBO = maintainerUserMap.get(businessTableFollowersBO.getUserId());
//                        BusinessTableFollowersVO businessTableFollowersVO = new BusinessTableFollowersVO();
//                        businessTableFollowersVO.setId(businessTableRecordBO.getId());
//                        businessTableFollowersVO.setName(userInfoBO.getName());
//                        businessTableFollowersVO.setFollowersType(BusinessRecordConstants.FollowersType.MAINTAINER.name());
//                        businessTableFollowersVO.setUserId(businessTableFollowersVO.getUserId());
//                        maintainerOfRecordVOList.add(businessTableFollowersVO);
//                    }
//                }
//                businessTableRecordVO.setMaintainerList(maintainerOfRecordVOList);


                //设置关注人
                List<BusinessTableFollowersVO> followersOfRecordVOList = new ArrayList<>();
                List<BusinessTableFollowersBO> followersOfRecordList = followerOfRecordMap.get(businessTableRecordBO.getId());
                if(!CollectionUtils.isEmpty(followersOfRecordList)){
                    for (BusinessTableFollowersBO businessTableFollowersBO:followersOfRecordList){
                        UserInfoBO userInfoBO = followersUserMap.get(businessTableFollowersBO.getUserId());
                        BusinessTableFollowersVO businessTableFollowersVO = new BusinessTableFollowersVO();
                        businessTableFollowersVO.setId(businessTableRecordBO.getId());
                        businessTableFollowersVO.setName(userInfoBO.getName());
                        businessTableFollowersVO.setFollowersType(BusinessRecordConstants.FollowersType.FOLLOWERS.name());
                        businessTableFollowersVO.setUserId(businessTableFollowersVO.getUserId());
                        followersOfRecordVOList.add(businessTableFollowersVO);
                    }
                }
                businessTableRecordVO.setFollowersList(followersOfRecordVOList);
                businessTableRecordVOList.add(businessTableRecordVO);
            }
            return PageDataUtil.getPageData(pageData.getTotalCount(),businessTableRecordVOList);
        }
        return PageDataUtil.getEmptyData();
    }


}
